package heven.holt.wan.android.binding

import android.view.LayoutInflater
import androidx.databinding.BindingAdapter
import androidx.navigation.findNavController
import com.google.android.flexbox.FlexboxLayout
import heven.holt.wan.android.MainFragmentDirections
import heven.holt.wan.android.databinding.ItemNavigationLinkContentBinding
import heven.holt.wan.android.model.ProjectTreeModel

@BindingAdapter("android:navigation_tree")
fun bindNavigationTree(flexboxLayout: FlexboxLayout, list: List<ProjectTreeModel>) {
    flexboxLayout.removeAllViews()
    list.forEach { projectTreeModel ->
        val itemBinding = ItemNavigationLinkContentBinding.inflate(
            LayoutInflater.from(flexboxLayout.context),
            flexboxLayout,
            false
        )
        itemBinding.root.text = projectTreeModel.name
        itemBinding.root.setOnClickListener { view ->
            if (projectTreeModel.id == null || projectTreeModel.id == 0) return@setOnClickListener
            val direction =
                MainFragmentDirections.actionMainFragmentToSystemFragment(projectTreeModel.id)
            view.findNavController().navigate(direction)
        }
        flexboxLayout.addView(itemBinding.root)
    }
}